package com.yfp.system.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.StringUtils;
import com.yfp.common.core.utils.poi.ExcelUtil;
import com.yfp.common.core.utils.sign.RsaUtils;
import com.yfp.common.core.web.controller.BaseController;
import com.yfp.common.core.web.domain.AjaxResult;
import com.yfp.common.core.web.page.TableDataInfo;
import com.yfp.common.log.annotation.Log;
import com.yfp.common.log.enums.BusinessType;
import com.yfp.common.security.annotation.InnerAuth;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.system.api.domain.SysDept;
import com.yfp.system.api.domain.SysRole;
import com.yfp.system.api.domain.SysUser;
import com.yfp.system.api.model.LoginUser;
import com.yfp.system.domain.vo.SysUserVO;
import com.yfp.system.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 *
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户管理")
public class SysUserController extends BaseController {
    @Resource
    private ISysUserService userService;

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysDeptService deptService;

    @Resource
    private ISysPostService postService;

    @Resource
    private ISysPermissionService permissionService;

    @Resource
    private ISysConfigService configService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取用户列表", description = "获取用户列表")
    public TableDataInfo list(SysUser user, Integer pageNum, Integer pageSize) {
        return getDatableByStream(userService.getUserList(user), pageNum, pageSize);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @Operation(summary = "用户管理导出", description = "用户管理导出")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUserVO> list = userService.getUserList(user);
        ExcelUtil<SysUserVO> util = new ExcelUtil<SysUserVO>(SysUserVO.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @Operation(summary = "用户管理导入", description = "用户管理导入")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }


    @PostMapping("/importTemplate")
    @Operation(summary = "用户管理导入", description = "用户管理导入")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    @Operation(summary = "获取当前用户信息", description = "获取当前用户信息")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }


    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/infoByPhone/{phone}")
    @Operation(summary = "获取当前用户信息", description = "获取当前用户信息")
    public R<LoginUser> infoByPhone(@PathVariable("phone") String phone) {
        SysUser byUserNameSysUser = userService.selectUserByUserName(phone);
        if (StringUtils.isNull(byUserNameSysUser)) return R.fail("用户名或密码错误");
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(byUserNameSysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(byUserNameSysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(byUserNameSysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @InnerAuth
    @GetMapping("/info/phone/{phone}")
    @Operation(summary = "获取用户信息", description = "获取用户信息")
    public R<LoginUser> getOperationUserInfoByPhone(@PathVariable("phone") String phone) {
        SysUser sysUser = userService.selectUserByPhone(phone);
        log.info("sysUser:{}", JSON.toJSONString(sysUser));
        if (StringUtils.isNull(sysUser)) {
            return R.fail("账号不存在");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        log.info("roles:{}", JSON.toJSONString(roles));
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        log.info("permissions:{}", JSON.toJSONString(permissions));
        // 角色详情集合
        List<SysRole> roleInfos = roleService.selectRolesByUserId(sysUser.getUserId());
        log.info("roleInfos:{}", JSON.toJSONString(roleInfos));
        roleInfos = roleInfos.stream().filter(r -> r.isFlag()).collect(Collectors.toList());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setRolesInfoList(roleInfos);

        log.info("LoginUser:{}", JSON.toJSONString(sysUserVo));
        return R.ok(sysUserVo);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @InnerAuth
    @GetMapping("/info/user/{userId}")
    @Operation(summary = "获取用户信息", description = "获取用户信息")
    public R<LoginUser> getOperationUserInfoByUser(@PathVariable("userId") Long userId) {
        SysUser sysUser = userService.getByUserId(userId);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("账号不存在");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        // 角色详情集合
        List<SysRole> roleInfos = roleService.selectRolesByUserId(sysUser.getUserId());
        roleInfos = roleInfos.stream().filter(r -> r.isFlag()).collect(Collectors.toList());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setRolesInfoList(roleInfos);
        return R.ok(sysUserVo);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @InnerAuth
    @GetMapping("/info/group/{phone}")
    @Operation(summary = "获取用户信息", description = "获取用户信息")
    public R<LoginUser> getGroupUserInfoByPhone(@PathVariable("phone") String phone) {
        SysUser sysUser = userService.selectUserByUserName(phone);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("账号不存在");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        // 角色详情集合
        List<SysRole> roleInfos = roleService.selectRolesByUserId(sysUser.getUserId());
        roleInfos = roleInfos.stream().filter(r -> r.isFlag()).collect(Collectors.toList());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setRolesInfoList(roleInfos);
        return R.ok(sysUserVo);
    }

    /**
     * 用户重置密码
     */
    @InnerAuth
    @PostMapping("updateUserInfo")
    @Operation(summary = "用户重置密码", description = "用户重置密码")
    public R<LoginUser> updateUserInfo(@RequestBody SysUser sysUser) {
        SysUser user = userService.selectUserByUserName(sysUser.getUserName());
        if (ObjectUtil.isNull(user)) {
            return R.fail("更新'" + sysUser.getPhonenumber() + "'失败，账号不存在");
        }
        return userService.resetUserPwd(user.getUserName(), SecurityUtils.encryptPassword(sysUser.getPassword())) == 1 ? R.ok() : R.fail("修改密码异常，请联系管理员");
    }


    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    @Operation(summary = "注册用户信息", description = "注册用户信息")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        if (!userService.checkPhoneUnique(sysUser)) {
            return R.fail("保存用户'" + sysUser.getPhonenumber() + "'失败，手机号码已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    @Operation(summary = "获取用户信息", description = "获取用户信息")
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        SysUser user = userService.selectUserById(userId);
        if (ObjectUtil.isNull(user)) return AjaxResult.error("未获取到用户信息");
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        user.setPassword("");
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = {"/", "/{userId}"})
    @Operation(summary = "根据用户编号获取详细信息", description = "根据用户编号获取详细信息")
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
//        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        SysRole sysRole = new SysRole();
        List<SysRole> roles = roleService.selectRoleList(sysRole);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).toList());
//        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = userService.selectUserById(userId);
            sysUser.setPassword("");
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).toList());
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Operation(summary = "新增用户", description = "新增用户")
    public AjaxResult add(@Validated @RequestBody SysUser user) throws Exception {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (!userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getPhonenumber() + "'失败，手机号码已存在");
        }
        Validator.validateMobile(user.getUserName(), "账号格式不正确");
        String password = RsaUtils.decryptByPrivateKey(user.getPassword());
        user.setCreateBy(SecurityUtils.getLoginUser().getSysUser().getNickName());
        user.setPassword(SecurityUtils.encryptPassword(password));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Operation(summary = "修改用户", description = "修改用户")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        logger.info("user：{}", user);

        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (!userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getPhonenumber() + "'失败，手机号码已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    @Operation(summary = "删除用户", description = "删除用户")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    @Operation(summary = "重置密码", description = "重置密码")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        int i = userService.resetPwd(user);
        log.info("重置密码；{}", user);
        return toAjax(i);
    }

    /**
     * 状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @Operation(summary = "状态修改", description = "状态修改")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user.getUserId(), user.getStatus()));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    @Operation(summary = "根据用户编号获取授权角色", description = "根据用户编号获取授权角色")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).toList());
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    @Operation(summary = "用户授权角色", description = "用户授权角色")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    @Operation(summary = "获取部门树列表", description = "获取部门树列表")
    public AjaxResult deptTree(SysDept dept) {
        return success(deptService.selectDeptTreeList(dept));
    }


    /**
     * 获取部门树列表
     */
    @GetMapping("/verifyPhone")
    @Operation(summary = "验证手机号码", description = "验证手机号码")
    public AjaxResult verifyPhone(@RequestBody SysUser sysUser) {
        return success(userService.verifyPhone(sysUser));
    }


    /**
     * 根据角色类型查询用户列表
     *
     * @param roleId
     * @return
     */
    @GetMapping("getUserByRoleId")
    @Operation(summary = "根据角色类型查询用户列表", description = "根据角色类型查询用户列表")
    public AjaxResult getUserByRoleId(Integer roleId) {
        return success(userService.roleUserList(roleId));
    }

    /**
     * 根据手机号获取用户信息
     *
     * @param phonenumber
     * @return
     */
    @GetMapping("getByMoble")
    @Operation(summary = "根据手机号获取用户信息", description = "根据手机号获取用户信息")
    public AjaxResult getByMoble(String phonenumber) {
        return success(userService.selectUser(phonenumber));
    }


    @PostMapping("/add")
    @Operation(summary = "团餐审核通过添加用户")
    public R<Long> addUser(@Validated @RequestBody SysUser user) {
        Long userId = userService.add(user);
        return R.ok(userId);
    }

    @InnerAuth
    @PutMapping("/updateAvatar")
    @Operation(summary = "h5-头像修改", description = "h5-我的账号-用户头像修改")
    public R<Void> updateAvatar(@RequestParam("avatarUrl") String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return R.ok();
    }


    /**
     * 根据账号获取用户信息
     *
     * @param userName
     * @return
     */
    @PostMapping("/getByUserName")
    @Operation(summary = "根据账号获取用户信息", description = "根据账号获取用户信息")
    public AjaxResult getByUserName(@RequestParam("userName") String userName) {
        return success(userService.getByUserName(userName));
    }
}
